<!-- 供货商商品管理页面 -->
<template>
  <div>
    <base-table ref="table" :search-params="searchParams" :columns="columnsAction" :async-fc="page">
      <template #tableHeader>
        <t-button @click="insert">新增商品</t-button>
      </template>
    </base-table>
    <t-dialog v-model:visible="modalOpen" width="45%" @confirm="onModalSubmit">
      <t-form ref="submitFormRef" style="width: 100%" :rules="rules" :data="submitForm" label-align="top">
        <t-row style="width: 100%" :gutter="[16, 16]">
          <t-col :span="6">
            <t-form-item label="商品名称" name="name">
              <t-input v-model="submitForm.name" placeholder="请输入商品名称" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="商品封面" name="name">
              <common-upload
                v-model:value="submitForm.cover"
                value-type="string"
                :limit="5"
                :tip="'请上传封面图'"
              ></common-upload>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="价格" name="price">
              <t-input-number v-model="submitForm.price" :min="0" :step="0.01" placeholder="请输入价格" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="库存" name="stock">
              <t-input-number v-model="submitForm.stock" :min="0" :step="1" placeholder="请输入库存" />
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item label="状态" name="status">
              <t-select v-model="submitForm.status" placeholder="请选择状态">
                <t-option :value="0" label="下架" />
                <t-option :value="1" label="上架" />
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item label="商品描述" name="description">
              <rich-editor v-model="submitForm.description" />
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { FormInstanceFunctions, Image, Link, MessagePlugin, Space, Tag } from 'tdesign-vue-next';
import { computed, ref } from 'vue';

import { insertApi, page, updateApi } from '@/api/goods';
import baseTable from '@/components/base-table/index.vue';
import CommonUpload from '@/components/common-upload/index.vue';
import RichEditor from '@/components/rich-editor/index.vue';
import { formatDate } from '@/utils/format';

const submitForm = ref<any>({});
const modalOpen = ref(false);
const submitFormRef = ref<FormInstanceFunctions>(null);
const table = ref<any>(null);

// 搜索参数
const searchParams = computed(() => [
  {
    key: 'name',
    label: '商品名称',
    hide: false,
  },
  {
    type: 'select',
    key: 'status',
    label: '状态',
    valueType: 'select',
    defaultValue: 1,
    options: [
      { label: '下架', value: 0 },
      { label: '上架', value: 1 },
    ],
  },
]);

// 表单校验规则
const rules = computed(() => ({
  name: [{ required: true, message: '请输入商品名称' }],
  price: [{ required: true, message: '请输入价格' }],
  stock: [{ required: true, message: '请输入库存' }],
  status: [{ required: true, message: '请选择状态' }],
  description: [{ required: true, message: '请输入商品描述' }],
}));

// 表格列定义
const columns = computed(() => [
  {
    title: '商品名称',
    colKey: 'name',
  },
  {
    title: '商品封面',
    colKey: 'cover',
    align: 'center',
    cell: (h, { row }) =>
      h(Image, {
        src: JSON.parse(row.cover)[0]?.data,
        fit: 'contain',
        style: 'width: 100px; height: 100px;margin: 0 auto',
      }),
  },
  {
    title: '价格',
    colKey: 'price',
  },
  {
    title: '库存',
    colKey: 'stock',
  },
  {
    title: '状态',
    colKey: 'status',
    cell: (h, { row }) => {
      const statusMap = {
        0: { text: '下架', theme: 'danger' },
        1: { text: '上架', theme: 'success' },
      };
      const status = statusMap[row.status];
      return h(Tag, { theme: status.theme }, () => status.text);
    },
  },
  {
    title: '创建时间',
    colKey: 'createTime',
    cell: (h, { row }) => formatDate(row.createTime),
  },
]);

// 表格列定义（带操作列）
const columnsAction = computed(() => [
  ...columns.value,
  {
    title: '操作',
    colKey: 'op',
    align: 'center',
    cell: (h, { row }) => {
      const buttons = [
        h(
          Link,
          {
            theme: 'primary',
            onClick: () => {
              submitForm.value = { ...row };
              modalOpen.value = true;
            },
          },
          () => '编辑',
        ),
      ];

      // 根据状态显示不同的操作按钮
      if (row.status === 0) {
        buttons.push(
          h(
            Link,
            {
              theme: 'success',
              onClick: () => updateStatus(row.id, 1),
            },
            () => '上架',
          ),
        );
      } else {
        buttons.push(
          h(
            Link,
            {
              theme: 'warning',
              onClick: () => updateStatus(row.id, 0),
            },
            () => '下架',
          ),
        );
      }

      return h(Space, {}, () => buttons);
    },
  },
]);

// 新增商品
const insert = () => {
  modalOpen.value = true;
  submitForm.value = {
    type: 1, // 供货商商品
    status: 0, // 默认下架
  };
};

// 更新商品状态
const updateStatus = async (id: number, status: number) => {
  try {
    await updateApi({ id, status });
    MessagePlugin.success('操作成功！');
    table.value.onSearch();
  } catch (error) {
    console.error(error);
  }
};

// 提交表单
const onModalSubmit = async () => {
  const valid = await submitFormRef.value.validate();
  if (valid === true) {
    if (submitForm.value.id) {
      await updateApi(submitForm.value);
    } else {
      await insertApi(submitForm.value);
    }
    MessagePlugin.success('操作成功！');
    modalOpen.value = false;
    table.value.onSearch();
  }
};
</script>

<style lang="less" scoped></style>
